<?php
/*
 * @See Clu_Db_Table_Abstract
 */
class product_Model_Product extends Zend_Db_Table_Abstract
{
	//only specify the table name, everything else inherits
    	protected $_name = "user_company_products";
    	protected $_primary = "id";
    
	public function findByPrimary($id)
	{
		if (!$id)
            return null;
        else
		    return $this->fetchRow('id = ' . $this->getAdapter()->quote($id, 'INTEGER'));
	}
	

	public function insertRaw($data ,$doValidate = false)
	{ 
		$n = array();
	    $n['title']        = $data['title']; 
	   	if(isset($data['id']))
	    	$n['user_id']    = $data['id'];
		$n['price']      = $data['price'];
		$n['desc']      = $data['desc'];
		/*
        $auth = Zend_Auth::getInstance();
	    $n['poster_id'] 	= $auth->getIdentity()->id;
	    */
		return $this->insert($n);
	}
	
	public function saveRaw($n, $data, $id, $doValidate)
	{
	    if((!$n) && (!$id))
	    	return false;
	    else if(!$n)
	       	if(!$n = $this->findByPrimary($id))
	       		return false;

	    if ($doValidate)
	    {
	    	//Validate Data here
	    }
		$temp = array();
	    $temp['title']        = $data['title']; 
	   	if(isset($data['id']))
	    	$temp['user_id']    = $data['id'];
		$temp['price']      = $data['price'];
		$temp['desc']      = $data['desc'];
	    $n->setFromArray($temp);
        return $n->save();
	}
	
	public function search($data)
	{	
		
		$title 		= 	isset($data['title'])    ?  $data['title'] : null;
		$price 		= 	isset($data['price'])    ?  $data['price'] : null; 
		$desc 		=	isset($data['desc'])     ?  $data['desc']  : null;
		$db = $this->getAdapter();
		$select = $db->select();
	    //  ->distinct();
		//    Add a FROM clause
	    $select->from( array('p' => "user_company_products") );
	    $select->where('p.user_id = ?',$db->quoteinto($data['user_id'],"INTEGER"));
		
		return $select;
	}
	
	public function deleteByPrimary($idArray, $atomic = true)
	{
       	$auth = Zend_Auth::getInstance();
     	$uIdentity = $auth->getIdentity();
     	$sess = new Zend_Session_Namespace(CLU_NS);
        if (!$auth->hasIdentity())
		{
		 	$this->view->errorMessage = t(310);
            $this->renderToHolder('common/error.phtml');
            return;
		}
		
		$auth = Zend_Auth::getInstance();
        $db = $this->getAdapter();
        
        if ($atomic)
	        $db->beginTransaction(); //@NOTE: no effect with MyISAM
	        
    
            try
            {
                $sql = "DELETE FROM user_company_products WHERE id IN (". $db->quote($idArray, 'INTEGER') .")" ;
               	$db->query($sql);
              //  $aModel->deleteByPrimary($articleIds,false); //non atomic
               	if ($atomic)
    	            $db->commit();
                return true;
        	}
            catch (Exception $e)
            {
                if ($atomic)
    	            $db->rollBack();
                return false;
            }
	}
	
}
?>
